package com.ibpd.henuocms.tlds;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;

import org.h2.util.StringUtils;
import org.hsqldb.lib.StringUtil;

import com.ibpd.dao.impl.ServiceProxyFactory;
import com.ibpd.henuocms.assist.ExtContentEntity;
import com.ibpd.henuocms.common.IbpdLogger;
import com.ibpd.henuocms.common.TimeHelper;
import com.ibpd.henuocms.entity.ContentAttrEntity;
import com.ibpd.henuocms.entity.ContentEntity;
import com.ibpd.henuocms.entity.NodeAttrEntity;
import com.ibpd.henuocms.entity.SubSiteEntity;
import com.ibpd.henuocms.entity.ext.ContentExtEntity;
import com.ibpd.henuocms.service.content.ContentServiceImpl;
import com.ibpd.henuocms.service.content.IContentService;
import com.ibpd.henuocms.service.nodeAttr.INodeAttrService;
import com.ibpd.henuocms.service.nodeAttr.NodeAttrServiceImpl;
import com.ibpd.henuocms.service.subSite.ISubSiteService;
import com.ibpd.henuocms.service.subSite.SubSiteServiceImpl;
import com.ibpd.henuocms.web.controller.web.WebSite;

public class ContentTag extends SimpleBaseTag {
	private String contentId="";
	private String valueVar="";

	private Object value;	
	private String field="";
	private String dateFormat="";
	private String escape="";
	private ExtContentEntity content=null;
	public String getField() {
		return field;
	}

	public void setField(String field) {
		this.field = field;
	}
	public String getContentId() {
		return contentId;
	}

	public void setContentId(String contentId) {
		this.contentId = contentId;
	}
	public void setValue(Object value) {
		this.value = value;
	}

	@Override
	public void doTag() throws JspException, IOException {
		_init();
		if(content==null){
            return ;
            }
	    getJspContext().getOut().write(getFieldValue(content,field));
	    if(getJspBody()!=null)
	       	getJspBody().invoke(null);
	}
	public String getValueVar() {
		return valueVar;
	}

	public void setValueVar(String valueVar) {
		this.valueVar = valueVar;
	}
	private void _init() {
		if(!StringUtils.isNullOrEmpty(valueVar) && value==null){
			value=getJspContext().getAttribute(valueVar);
		}
		if(value==null){
			if(!StringUtil.isEmpty(this.contentId)){
				if(contentId.toUpperCase().equals("OWNER")){
					contentId=getRequest().getParameter("contentId");
				}
			}
			if(StringUtils.isNumber(contentId)){
				IContentService contService=(IContentService) ServiceProxyFactory.getServiceProxy(ContentServiceImpl.class);
				value=contService.getContentExtEntity(Long.parseLong(contentId));
			}
		}
		if(value!=null){
			if(value instanceof ExtContentEntity){
				content=(ExtContentEntity) value;
			}else if(value instanceof ContentExtEntity){
				ContentExtEntity t=(ContentExtEntity) value;
				ExtContentEntity c=new ExtContentEntity(t.getContent());
				c.setAttrEntity(t.getAttr());
				content=c;
			}
		}else{
			ContentEntity c=new ContentEntity();
			c.setTitle("[error]未获取到内容");
			content=new ExtContentEntity(c);
		}
		if(StringUtil.isEmpty(field)){
			field="title";
		}
	}
	private String getFieldValue(ExtContentEntity cntExtEntity,String fieldName){
		String rtn="";
		if(cntExtEntity==null)
			return "";
		Object obj=cntExtEntity;
		if(obj==null)
			return "";
		else{
			try{
				String getFunName="get"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);
				if(!existMethod(getFunName,obj)){
					ContentAttrEntity attr=cntExtEntity.getAttrEntity();
					if(attr==null && !fieldName.toUpperCase().trim().equals("FULLURL") && !fieldName.toUpperCase().trim().equals("SHORTURL"))
						return ""; 
					else{
						if(!existMethod(getFunName,attr)){
							//如果在node和attr中都没有该属性，那么就有可能是前台让返回url目录或者字段信息错误
							String path = getRequest().getContextPath();
							if(!checkViewerMode()){
								path="";
							}
							if(fieldName.toUpperCase().trim().equals("FULLURL")){
								path = getRequest().getContextPath();
								String basePath = getRequest().getScheme()+"://"+getRequest().getServerName()+":"+getRequest().getServerPort()+path+"/";
								String dir="";
								if(getRequest().getParameter("type")!=null && getRequest().getParameter("type").toLowerCase().trim().equals(WebSite.WEBPAGE_TYPE_VIEWER.toLowerCase())){
									dir="sites/";
								}
								dir+=getContentUrlDir(cntExtEntity);
								return basePath+dir;
							}else if(fieldName.toUpperCase().trim().equals("SHORTURL")){
								
								String dir="";
								if(checkViewerMode()){
									path = getRequest().getContextPath()+"/";
									dir="sites/";
								}else{
									path="/";
									dir="";
								}
								dir+=getContentUrlDir(cntExtEntity);
								return path+dir;
							}else{
								return "field设置错误";
							}
						}else{
							Method funMethod=attr.getClass().getMethod(getFunName, new Class[]{});
							rtn=getReturnValue(funMethod,attr);
						}
					}
				}else{
					Method funMethod=obj.getClass().getMethod(getFunName, new Class[]{});
					rtn=getReturnValue(funMethod,obj);
				}
			}catch(Exception e){
				e.printStackTrace();
				
			}
			if(!checkViewerMode()){
				Long siteId=cntExtEntity.getSubSiteId();
				ISubSiteService siteServ=(ISubSiteService) ServiceProxyFactory.getServiceProxy(SubSiteServiceImpl.class);
				SubSiteEntity s=siteServ.getEntityById(siteId);
				if(s!=null)
					rtn=rtn.replace("/sites/"+s.getDirectory(), "").replace("\"//", "\"/").replace("'//", "'/");
			}
			return rtn;
		}
	} 
	private Boolean existMethod(String mtName,Object obj){
		if(obj==null)
			return false;
		Method[] mts=obj.getClass().getMethods();
		for(Method mt:mts){
			if(mt.getName().equals(mtName)){
				return true;
			}
		}
		return false;
	}
	private String getContentUrlDir(ExtContentEntity cnt){
		if(cnt==null)
			return ""; 
		ISubSiteService siteServ=(ISubSiteService) ServiceProxyFactory.getServiceProxy(SubSiteServiceImpl.class);
		SubSiteEntity site=siteServ.getEntityById(cnt.getSubSiteId());
		if(site==null)
			return "";
		String idPath=cnt.getNodeIdPath();
		String[] ids=idPath.split(",");
		Map<Long,String> dirMap=new LinkedHashMap<Long,String>();
		//先把要取的目录都取出来
		if(checkViewerMode())
			dirMap.put(site.getId(), site.getDirectory());
		INodeAttrService attrService=(INodeAttrService) ServiceProxyFactory.getServiceProxy(NodeAttrServiceImpl.class);
		for(String id:ids){
			if(StringUtil.isEmpty(id))
				continue;
			if(StringUtils.isNumber(id)){
				Long nodeId=Long.parseLong(id);
				NodeAttrEntity attr=attrService.getNodeAttr(nodeId);
				if(attr!=null){
					dirMap.put(nodeId, attr.getDirectory());//理论上这里取出来的目录顺序是正确的，这里之所以要把目录放入跟ID对照的map中，是为了以后扩展方便
				}
			}
			
		}
		String dir="";
		for(Long key:dirMap.keySet()){
			dir+=dirMap.get(key)+"/";
		}
		dir=dir+"cnt-"+cnt.getId()+".html";
		return dir;
	}
	private String getReturnValue(Method mthod,Object obj) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		Object rtn=mthod.invoke(obj, null);
		rtn=rtn==null?"":rtn;
		String rtnString=""; 
		if(mthod.getReturnType().getSimpleName().equals("Date")){
			if(!StringUtil.isEmpty(dateFormat)){
				rtnString = TimeHelper.getDate((Date)rtn, dateFormat);
			}else{
				rtnString=escapeValue(rtn.toString(),this.getEscape());
			}
		}else{
			rtnString=rtn.toString();
		}
		rtnString=escapeValue(rtnString,this.getEscape());
		return rtnString;
	}

	@Override
	protected void init() {
		IbpdLogger.getLogger(this.getClass()).info("init");
		value=null; 

	}

	public void setDateFormat(String dateFormat) {
		this.dateFormat = dateFormat;
	}

	public String getDateFormat() {
		return dateFormat;
	}

	public void setEscape(String escape) {
		this.escape = escape;
	}

	public String getEscape() {
		return escape;
	}

}